﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Dln.Common;
using Dln.Common.Helper;
using Dln.Handler;
using Dln.Model;
using Dln.Common.WxPayAPI;

public partial class Page_Customer_AllPatient : BasePage
{
    public string openid = string.Empty;
    public PatientInfo Model = null;
    protected void Page_Load(object sender, EventArgs e)
    {
       var aa= DateTime.Now.AddMonths(-1);
        openid = GetAuthOpenId();
        //openid = "orrZmw6biSbZglMMLFS4eB81nycM";
        string code = DNTRequest.GetString("from");
        if (!string.IsNullOrEmpty(code) && code == "jspay")
        {
            var BuildCardRecordList = SqlHelper.Context.FromSql(" select top 1 * from BuildCardRecord where openid = '" + openid + "' and DelStatus = 0 and(HISCardID is not null and HISCardID != '') and(payno is not null and payno != '')  order by PayTime").ToList<BuildCardRecord>();
            if (BuildCardRecordList != null && BuildCardRecordList.Count > 0)
            {
                var uptModel =
                   SqlHelper.Context.From<PatientInfo>()
                       .Where(d => d.PatientPatiID == BuildCardRecordList.FirstOrDefault().HISCardID && d.Delstatus == 0 && d.Openid == openid)
                       .First();
                var uptModel1 =
                    SqlHelper.Context.From<PatientInfo>()
                        .Where(d => d.PatientPatiID == BuildCardRecordList.FirstOrDefault().HISCardID && d.Delstatus == 1 && d.Openid == openid)
                        .First();
                if (uptModel != null)
                {
                    Model = uptModel;
                    return;
                }
                if (uptModel1 != null)
                {
                    uptModel1.Delstatus = 0;
                    uptModel1.PatientIdCard = BuildCardRecordList.FirstOrDefault().PatiIdCard;
                    uptModel1.PatientPhone = BuildCardRecordList.FirstOrDefault().PatiPhone;
                    uptModel1.PatientName = BuildCardRecordList.FirstOrDefault().PatiName;
                    uptModel1.PatientPatiID = BuildCardRecordList.FirstOrDefault().HISCardID;
                    uptModel1.Openid = openid;
                    var updateResult = SqlHelper.Context.Update<PatientInfo>(uptModel1);
                    if (updateResult > 0)
                    {
                        Model = uptModel1;
                        return;
                    }
                }
                var model = new PatientInfo();
                model.AddTime = DateTime.Now;
                model.PatientIdCard = BuildCardRecordList.FirstOrDefault().PatiIdCard;
                model.PatientPhone = BuildCardRecordList.FirstOrDefault().PatiPhone;
                model.PatientName = BuildCardRecordList.FirstOrDefault().PatiName;
                model.PatientPatiID = BuildCardRecordList.FirstOrDefault().HISCardID;
                model.Openid = openid;
                var insertResult = SqlHelper.Context.Insert<PatientInfo>(model);
                if (insertResult > 0)
                {
                    Model = model;
                    return;
                }
            }
        }
        else
        {
            Model = SqlHelper.Context.From<PatientInfo>().Where(d => d.Openid == openid && d.Delstatus == 0).First();
        }

    }

    public string GetAuthOpenId()
    {
        string AppId = CommonHelper.GetAppSettings("AppID");
        string AppSecret = CommonHelper.GetAppSettings("AppSecret");
        string strOpenId = "";
        string name = "";
        string code = DNTRequest.GetString("CODE");

        var cookies = HttpContext.Current.Request.Cookies["openidcookie"];
        if (cookies != null && !string.IsNullOrEmpty(cookies.Value))
        {
            strOpenId = cookies.Value;
        }
        else
        {
            if (!String.IsNullOrEmpty(code))
            {
                string json = RequestHelper.SendGet(String.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", AppId, AppSecret, code));
                if (!String.IsNullOrEmpty(json))
                {
                    try
                    {
                        OAuthConfig oAuthConfig = JSONHelper.FromJson<OAuthConfig>(json);
                        if (oAuthConfig != null)
                        {
                            HttpCookie cookie = new HttpCookie("openidcookie");
                            cookie.Value = oAuthConfig.openid;
                            cookie.Expires = DateTime.Now.AddDays(2);
                            HttpContext.Current.Response.Cookies.Add(cookie);
                            strOpenId = oAuthConfig.openid;
                        }

                        else
                        {
                            strOpenId = "";
                        }
                    }
                    catch (Exception ex)
                    {
                        strOpenId = "";
                    }
                }
            }
            else
            {
                var url = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}%2FPage%2FCustomer%2FAllPatient.aspx&response_type=code&scope=snsapi_base&state=test#wechat_redirect", AppId, CommonHelper.GetAppSettings("mainurl").Replace(@"://", "%3A%2F%2F"));
                Response.Redirect(url);

            }
        }
        return strOpenId;
    }
}